#include "udp_client.h"
#include <stdio.h>
#include "hilog.h"
//udp datagram max len
#define MAX_UDP_LEN 65507
UdpClient::UdpClient()
{
    sockfd_ = -1;
    port_ = -1;
    memset(ip_, 0, 20);
    memset(&addr_, 0, sizeof(struct sockaddr_in));
}

UdpClient::~UdpClient()
{

}

int UdpClient::send_data_onece(const char *buf, int len, int port, const char *ip)
{
    for(int i = 0; i < 6; i++) {
        hi_trace("index: %d 0x%02x", i,buf[i]&0x000000ff);            
    }
    for(int i = 6; i < len; i++) {
        hi_trace("index:%d  %c", i, buf[i]);
    }
    
    if((len > MAX_UDP_LEN)||(len < 0)) {
        hi_error("send invalid data len: %d\n", len);
        return -1;
    }
    int bytes = 0;
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if (0>sockfd) {
         hi_error("creat socket failed! err:%d\n",errno);
         return -1;
    }

    struct sockaddr_in addr;
    int addr_len = sizeof(addr);
    memset(&addr, 0, addr_len);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip);

    bytes = sendto(sockfd,buf,len,0,(struct sockaddr *)&addr, addr_len);
    if(bytes<0) {
        hi_error("send ip %s udp data failed.err=%d\n", ip, errno);
        close(sockfd);
        return -1;
    }
    //hi_trace("send buf: %s len: %d to %s", buf,bytes,ip);

    close(sockfd);
    return bytes;
}

int UdpClient::init(int port, const char *ip)
{
    sockfd_ = create_sock();
    if(0 < sockfd_) {
        port_ = port;
        strcpy(ip_, ip);
        set_addr(port, ip);
    }
}

void UdpClient::uninit()
{
    if(sockfd_ > 0) {
        close(sockfd_);
    }
}

int UdpClient::send_data(const char *buf, int len)
{
    return sendto(sockfd_,buf,len,0,(struct sockaddr *)&addr_, sizeof(struct sockaddr));
}

int UdpClient::create_sock()
{
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if (0>sockfd) {
         printf("creat socket failed! err:%d\n",errno);
         return -1;
    }

    return sockfd;
}

void UdpClient::set_addr(int port, const char *ip)
{
    addr_.sin_family = AF_INET;
    addr_.sin_port = htons(port);
    addr_.sin_addr.s_addr = inet_addr(ip);
}
